# -*- coding:utf-8 -*-
from config import *


class Download(LineReceiver):
    # 缓冲流大小

    def __init__(self):
        self.fp = None
        self.status = None
        self.total = 0
        self.timer = MyTimer()
        self.echo = {
            "command": "download",
            "key": KEY
        }

    def dataReceived(self, data):
        if not self.status:
            ret = json.loads(data)
            self.echo['server_path'] = ret['server_path']
            if ret == self.echo:
                self.fp = open(ret['server_path'], "r")
                self.sendLine(data)
                self.status = status.LOOP
            else:
                self.stopProducing()
        elif self.status == status.LOOP:
            ret = json.loads(data)
            if ret == self.echo:
                while 1:
                    buf = self.fp.read(65536)
                    self.total += len(buf)
                    str = self.timer.get(self.total, os.path.getsize(ret['server_path']))
                    if str:
                        print str
                    if not buf: break
                    self.transport.write(buf)
            self.stopProducing()

    def connectionLost(self, reason):
        if self.fp: self.fp.close()
